package roles

import (
	"time"

	"gitee.com/cjianwen/go/demo/socks_v2/raft_demo/server/consts"
	"gitee.com/cjianwen/go/demo/socks_v2/raft_demo/server/global"
	"gitee.com/cjianwen/go/logs"
)

type follower struct {
	*roleState
	lastLearnIdx uint32
}

func (f *follower) Reset() {
	f.lastLearnIdx = global.DataEntries.GetIndex()
	global.NodeConns.CloseConns()
}

func (f *follower) Run() error {
	if f.IsPingTimeout() {
		logs.Println("ping 超时，成为候选人")
		f.becomeCandidate()
	}

	if global.LeaderConn == nil {
		return nil
	}

	if f.isAppending {
		if time.Since(f.appendingTime).Milliseconds() > consts.AppendTimeout {
			f.isAppending = false // 超时后修正状态
		}
	} else if f.lastLearnIdx < f.leaderPingDataIdx {

		f.lastLearnIdx = f.leaderPingDataIdx

		idx := global.DataEntries.GetCommitIdx()
		if f.lastLearnIdx > idx {
			logs.Printf("开始学习: %d -> %d", idx, f.lastLearnIdx)
			f.prot.SendLearn(global.DataEntries.GetIndex(), f.lastLearnIdx)
		}
	}

	return nil
}
